#!/usr/bin/python
# -*- coding: iso-8859-1 -*-
import wx
import os
import time
from time import sleep
from threadPool import threadPool
from settings import settings
from song import song
from fileScanner import fileScanner
import threadPool
from threadManager import threadManager

#import win32api
ID_ABOUT = 101
ID_EXIT  = 102
VERSION  = "0.2"

#******************************************************************************************************
class MyFrame(wx.Frame):
    def __init__(self, parent=None):
        self.mainFrame = wx.Frame.__init__(self, parent, wx.ID_ANY,'el manager', size=(400, 500))
#-------------------------------------------

#-------------------------------------------
        # GLOBAL VARS
        self.folderSelected = mysettings.getFolder()
        self.isSearching = False
        self.searching  = False
        self.totalFiles = 0
        self.totalFilesAnalizados = 0
        self.timer = None
#-------------------------------------------
        self.createButton()
        self.createProgressBar()
        self.createLogo()
        self.createSelectFolder()
        self.createMenu()
        self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)

        # MAR: intento de hacer funcionar el tree

        self.p = wx.Panel(self, -1,size=(400,500),pos=(15, 255))
        song1 = song("/folder/folder1/song1.mp3","mar 1","song 1")
        song2 = song("/folder/song2.mp3","mar 2","song 2")
        song3 = song("/folder/folder2/song3.mp3","mar 3","song 3")


        treeData = [song1,song2,song3]
        lastPath = ""
        #for item in treeData:
        #    lastPath = item.path
        #    
        #    print item.path
        self.createList( treeData )


#-------------------------------------------
        # set window icon
        #exeName = win32api.GetModuleFileName(win32api.GetModuleHandle(None))
        #icon = wx.Icon(exeName, wx.BITMAP_TYPE_ICO)
        #self.SetIcon(icon)

    def createMenu(self):
        menuBar = wx.MenuBar()
        menu = wx.Menu()
        # exit menu
        self.exit = menu.Append(-1, "Exit")
        self.Bind(wx.EVT_MENU, self.OnExit, self.exit)
		#MARTIN
        #self.Bind(wx.EVT_CLOSE, self.OnExit,self.mainFrame)
        menuBar.Append(menu, "Archivo")
        # opciones software
        self.menuOptions = wx.Menu()
        self.action1 = self.menuOptions.AppendCheckItem(1, "Auto-completar los metadatos")
        self.menuOptions.Check(1, mysettings.getAction1())
        self.Bind(wx.EVT_MENU, self.OnToggleActions, self.action1)
        self.action2 = self.menuOptions.AppendCheckItem(2, "Descartar metadatos antiguos")
        self.menuOptions.Check(2, mysettings.getAction2())
        self.Bind(wx.EVT_MENU, self.OnToggleActions, self.action2)
        self.action3 = self.menuOptions.AppendCheckItem(3, "Analizar solo la carpeta seleccionada")
        self.menuOptions.Check(3, mysettings.getAction3())
        self.Bind(wx.EVT_MENU, self.OnToggleActions, self.action3)
        self.menuOptions.AppendSeparator()
        self.option1 = self.menuOptions.AppendRadioItem(4, "Marcar en metadatos en el campo Comentarios")
        self.menuOptions.Check(4, mysettings.getOption1())
        self.Bind(wx.EVT_MENU, self.OnToggleOptions, self.option1)
        self.option2 = self.menuOptions.AppendRadioItem(5, "Mover la musica SGAE en carpetas")
        self.menuOptions.Check(5, mysettings.getOption2())
        self.Bind(wx.EVT_MENU, self.OnToggleOptions, self.option2)
        self.option3 = self.menuOptions.AppendRadioItem(6, "Eliminar la musica SGAE de mi ordenador")
        self.menuOptions.Check(6, mysettings.getOption3())
        self.Bind(wx.EVT_MENU, self.OnToggleOptions, self.option3)
        menuBar.Append(self.menuOptions, "Opciones")
        self.SetMenuBar(menuBar)
        # about menu

    def OnToggleActions(self, event):
        #if self.action1.IsChecked():
        #    print "action1 active!"
        #if self.action2.IsChecked():
        #    print "action2 active!"
        #if self.action3.IsChecked():
        #    print "action3 active!"
        mysettings.setAction1(self.action1.IsChecked())
        mysettings.setAction2(self.action2.IsChecked())
        mysettings.setAction3(self.action3.IsChecked())

    def OnToggleOptions(self, event):
        #if self.option1.IsChecked():
        #    print "option1 active!"
        #elif self.option2.IsChecked():
        #    print "option2 active!"
        #elif self.option3.IsChecked():
        #    print "option3 active!"
        mysettings.setOption1(self.option1.IsChecked())
        mysettings.setOption2(self.option2.IsChecked())
        mysettings.setOption3(self.option3.IsChecked())

#-------------------------------------------
    # evento cerrar ventana
    def OnCloseWindow(self, event):
        print "cerrar windows"
        self.Destroy()
        self.CancelAnalysis()

    def OnExit(self, event):
		#MARTIN:Cancelamos el analisis antes de cerrar para no dejar un hilo corriendo
		#if self.timer!=None:
			#self.CancelAnalysis()
		self.Close()
		
#-------------------------------------------
	    # Menu top
    def createLogo(self):
		# Logo
        self.bitmap = wx.Bitmap( 'elmanager2.png')
        wx.EVT_PAINT(self, self.OnPaint)
#-------------------------------------------
    def createSelectFolder(self):
		#MARTIN:thinner button so it doesn't hide the "analizar" button
        self.btn = wx.Button(self, -1, "Selecciona carpeta", size=(170,30),pos=(15, 100))
		#MARTIN:he cambiado los parentesis
        self.btn.SetLabel( (self.folderSelected!="" and  "Cambiar carpeta") or "Selecciona carpeta"   )
        self.Bind(wx.EVT_BUTTON, self.OnToggleItem, self.btn)
        self.folderPathLabel = wx.StaticText(self, label="",pos=(15, 130))
        self.folderPathLabel.SetLabel(self.folderSelected)

    def OnSelectFolder(self):
        dialog = wx.DirDialog ( None, "Seleccione la carpeta a analizar:",style=1 )
        if dialog.ShowModal() == wx.ID_OK:
          self.folderSelected = dialog.GetPath()
        dialog.Destroy()
        self.folderPathLabel.SetLabel(self.folderSelected)
        mysettings.setFolder(self.folderSelected)

#-------------------------------------------
    def createProgressBar(self):
		#MARTIN: pongo el parametro size por q si no se veia bien 
        self.version = wx.StaticText(self, label="",pos=(25, 185),size=(360, 28))
        self.version.SetLabel("Analizado 0/0")
        self.gauge = wx.Gauge(self, range=100, pos=(15, 205), size=(360, 28))
        self.gauge.SetValue(0)
        self.gauge.Hide()
        self.gauge.Show()

    def setPercentageAnalysis(self,value):
        self.gauge.SetValue(value)

    def OnPaint(self, event):
		dc = wx.PaintDC(self)
		dc.DrawBitmap(self.bitmap, 0, 0)

		
#-------------------------------------------
    def createButton(self):   
		self.button1 = wx.Button(self, -1, "Analizar", size=(170,30),pos=(15, 155))
		self.button1.Bind( wx.EVT_BUTTON, self.OnSearch)

    def UpdateSearchStatus(self):
		if(self.searchStatus == "listing"):
			self.version.SetLabel("Buscando archivos musica...("+str(myfileScanner.getTotal())+" encontrados)")
		elif(self.searchStatus == "analisis"):
			self.version.SetLabel("Analizado "+str(myThread.getTotalSongsAnalysed())+"/"+str(self.totalFiles))
			self.setPercentageAnalysis(myThread.getTotalSongsAnalysed()/float(self.totalFiles)*100)
			print "update analisis",myThread.poolSGAE.getThreadCount()
			if(myThread.isFinish()):
				self.timer.Stop()
				#MARTIN:cuando hemos acabado es cuando hacemos es Join
				myThread.endSGAEFinishProcess()
				self.version.SetLabel("Finalizado.")
				self.createList( myThread.getAllSongsAnalysed() )
				#MAR: para crear lista con canciones
				#self.createList( myThread.getAllSongsAnalysed() )
				
				#MARTIN:Este es un punto importante, parece que aqui es donde se generarÃÂ­a el informe y 
				#self.OnFinishAnalyse()
	#MARTIN: Cancelar el analisis			
    def CancelAnalysis(self, event=None):
			self.timer.Stop()
			myThread.endSGAEFinishProcess(False,False)
		
    def OnSearch(self, event):
        if(not self.searching):
			self.totalFiles = 0
			self.totalFilesAnalizados = 0
			self.button1.SetLabel("Stop Analisis")
			self.button1.Unbind( wx.EVT_BUTTON)
			self.button1.Bind( wx.EVT_BUTTON, self.CancelAnalysis)
			
			self.btn.Disable()

			self.timer = wx.PyTimer(self.UpdateSearchStatus)
			
			self.searchStatus = "listing"

			self.searching = True
			myfileScanner.scan(self.folderSelected)
			self.totalFiles = myfileScanner.getTotal()
			
			
			
			
			if( self.totalFiles==0):
				self.version.SetLabel("No se han encontrado archivos de sonido mp3 o ogg.")
				self.button1.SetLabel("Analizar")
				self.btn.Enable()
			else:
				self.searchStatus = "analisis"
				self.version.SetLabel("Analizado 0/"+str(self.totalFiles))
				#MARTIN: repintamos ahora actializar el "Analizando 0/..." de la linea de arriba
				self.Update()
				#solo lanzamos el timer si hay canciones
				self.timer.Start(500)
				myThread.startPool()
				myThread.addAllFiles()
                
        else:
            self.button1.SetLabel("Analizar")
            self.btn.Enable()
            self.searching = False
			#MARTIN:aqui quizÃÂ¡ deberia ir algo que "limpiara" el estado

    def OnToggleItem(self, event):
        self.OnSelectFolder()

#-------------------------------------------
# => display list folder and files analysed  
        

    def OnFinishAnalyse(self):
        self.createList()
        self.p.Show(True)

    def OnLoadIcons(self):
        self.iconspath = os.path.join(sys.prefix, "/icons")
        self.FolderOpenIcon = wx.Bitmap(os.path.join(iconspath, "folder_open_16.png"))
        self.FolderClosedIcon = wx.Bitmap(os.path.join(iconspath, "folder_close_16.png"))
        self.FileSGAEIcon = wx.Bitmap(os.path.join(iconspath, "music_sgae_16.png"))
        self.FileFreeIcon = wx.Bitmap(os.path.join(iconspath, "music_free_16.png"))
        self.ImageList = wx.ImageList(16, 16)
        self.FolderOpenIconIndex = self.ImageList.Add(self.FolderOpenIcon)
        self.FolderClosedIconIndex = self.ImageList.Add(self.FolderClosedIcon)
        self.FileSGAE = self.ImageList.Add(self.FileSGAEIcon)
        self.FileFree = self.ImageList.Add(self.FileFreeIcon)

    def createList(self, treeData):
        # How icons
        # Images icons
        il = wx.ImageList(16,16)
        self.fldridx = il.Add(wx.ArtProvider.GetBitmap(wx.ART_FOLDER, wx.ART_OTHER, (16,16)))
        self.fldropenidx = il.Add(wx.ArtProvider.GetBitmap(wx.ART_FILE_OPEN,   wx.ART_OTHER, (16,16)))
        self.fileidx = il.Add(wx.ArtProvider.GetBitmap(wx.ART_NORMAL_FILE, wx.ART_OTHER, (16,16)))
        # Create tree
        self.tree = wx.TreeCtrl(self.p, style=wx.TR_HIDE_ROOT| wx.TR_DEFAULT_STYLE | wx.TR_EDIT_LABELS, pos=(20, 0),size=(360, 200) )
        self.tree.AssignImageList(il)
        # Assign tree
        root = self.tree.AddRoot(self.folderSelected)
        self.tree.SetItemPyData(root, None)
        self.tree.SetItemImage(root, self.fldridx,wx.TreeItemIcon_Normal)
        self.tree.SetItemImage(root, self.fldropenidx,wx.TreeItemIcon_Expanded)
        # Root
        treeData.sort(key=self.getPath)
        rootOriginal = root
        lastFolder = ""
        # Ordenar datos para mostrar por carpeta (path)
        # Treure quins necessiten els arxius folders
        rootObj = {}
        rootObj[""] = root
        for itemTree in treeData:
             folderFromRoot = itemTree.path[len(self.folderSelected)+1:]
             print "*******************************"
             print "folderFromRoot: "+folderFromRoot
             file = folderFromRoot.split('/')[-1]
             folder = folderFromRoot[:-len(file)]
             print file+" - "+folder
             print lastFolder+" & "+folder
             #**********************
             if (lastFolder!=folder):
                rootFolder = ""
                try:
                    rootFolder = folderFromRoot[:-(len(file)+len(folder)+1)]
                    root = rootObj[rootFolder]
                except:
                    root = rootObj[""]
                    pass
                print "rootFolder: "+rootFolder
                print "new folder: "+ lastFolder
                lastFolder = folder[:-1]
                lastFolderStr = folder[:-1].split('/')[-1]
                print "lastFolderStr:"+lastFolderStr
                rootObj[lastFolder] = self.AddTreeNodes(root, lastFolderStr, True)
             print "lastFolder:"+lastFolder
             print "file:"+file
             #**********************
             try:
                root = rootObj[lastFolder]
             except:
                print "error"
                root = rootOriginal
                pass
             self.AddTreeNodes(root, file, False)

    def AddTreeNodes(self, parentItem, item, isFolder):
        newItem = self.tree.AppendItem(parentItem, item)
        self.tree.SetItemPyData(newItem, None)
        if isFolder==False:
            self.tree.SetItemImage(newItem, self.fileidx,wx.TreeItemIcon_Normal)
        else:
             self.tree.SetItemImage(newItem, self.fldridx,wx.TreeItemIcon_Normal)
             self.tree.SetItemImage(newItem, self.fldropenidx,wx.TreeItemIcon_Expanded)


#-------------------------------------------

if __name__ == '__main__':
    # auxiliar class 
    myfileScanner = fileScanner()
    myThread = threadManager( myfileScanner )
    mysettings = settings()
    app = wx.App(redirect=False)
    frame = MyFrame()
    frame.Show(True)
    app.MainLoop()

